package viper.ji;

/***************************************************
 * PBDataSource.java
 * -----------------------
 * Revision: v.1.0
 * Author: Ji Kim
 * Date Created: 11/13/2009
 * Description:
 *   Custom DataSource class for constructing DataSource
 *   compatible objects from a PushBufferStream created
 *   in the VIPER.java main method.
 * Last Back-Up: None, first revision
 * Revision History: None
 * -----------------------  
 * 
 * Based on the source code DataSource.java at the Sun
 * Developer Network:
 * http://java.sun.com/javase/technologies/desktop/
 *    media/jmf/2.1.1/solutions/LiveData.html#source
 ***************************************************/

import javax.media.Time;
import javax.media.MediaLocator;
import javax.media.protocol.*;
import java.io.IOException;

public class PBDataSource extends PushBufferDataSource {

	protected Object [] controls = new Object[0];
	protected boolean started = false;
	protected String contentType = "raw";
	protected boolean connected = false;
	protected Time duration = DURATION_UNKNOWN;
	protected PushBufferStream [] streams = null;
	protected PushBufferStream stream = null;

	public PBDataSource(PushBufferStream pbs) {
		stream = pbs;
		streams = new PushBufferStream [1];
		streams[0] = stream;
	}

	public String getContentType() {
		if (!connected){
			System.err.println("Error: DataSource not connected");
			return null;
		}
		return contentType;
	}

	public void connect() throws IOException {
		if (connected)
			return;
		connected = true;
	}

	public void disconnect() {
		try {
			if (started)
				stop();
		} catch (IOException e) {}
		connected = false;
	}

	public void start() throws IOException {
		// we need to throw error if connect() has not been called
		if (!connected)
			throw new java.lang.Error("DataSource must be connected before it can be started");
		if (started)
			return;
		started = true;
	}

	public void stop() throws IOException {
		if ((!connected) || (!started))
			return;
		started = false;
	}

	public Object [] getControls() {
		return controls;
	}

	public Object getControl(String controlType) {
		try {
			Class  cls = Class.forName(controlType);
			Object cs[] = getControls();
			for (int i = 0; i < cs.length; i++) {
				if (cls.isInstance(cs[i]))
					return cs[i];
			}
			return null;

		} catch (Exception e) {   // no such controlType or such control
			return null;
		}
	}

	public Time getDuration() {
		return duration;
	}

	public PushBufferStream [] getStreams() {
		return streams;
	}

}
